package com.applet.applet_shangcheng.controller;

import com.alibaba.fastjson.JSONObject;
import com.applet.applet_shangcheng.entity.Address;
import com.applet.applet_shangcheng.entity.Admin;
import com.applet.applet_shangcheng.entity.User;
import com.applet.applet_shangcheng.service.UserService;
import com.applet.applet_shangcheng.utlis.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin
@Api(value="用户管理",tags={"用户管理"})
public class UserController {
    @Autowired
    private UserService userServic;
    @ApiOperation(value="WX_推荐码加入")
    @GetMapping("/randomCode")
    public Result randomCode(){
        String code = AppletUtil.getRandomStringByLength(5);
        String CodeIdUser = userServic.selectCode(code);
        if (!StringUtils.isEmpty(CodeIdUser)){
            return new Result(false, StatusCode.ERROR,"推荐码已存在,请重试!");
        }
        return new Result(true, StatusCode.OK,"推荐码加入成功!",code);
    }
    @ApiOperation(value="PC_查询用户折线图")
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        Map<String,Object> map = new HashMap<String,Object>();
        // 存放日期的字符串集合（统计过去12个月）
        List<String> months = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        // 根据当前时间-12，算出12个月之前的时间
        calendar.add(Calendar.MONTH,-12);
        for(int i=1;i<=12;i++){
            calendar.add(Calendar.MONTH,1); //12个月之前的时间+1，得到2018-10
            months.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
        }
        List<Integer> memberCount = userServic.findMemberCountByRegTime(months);
        map.put("months",months);// 存的月份，List<String> :
        map.put("memberCount",memberCount);// 存放月份对应的数据，List<Integer>:[18,21,24]
        if (map==null){
            return new Result(false, StatusCode.ERROR,"查询失败!");
        }
        return new Result(true, StatusCode.OK,"查询成功!",map);
    }
    @ApiOperation(value="WX_获取openId")
    @GetMapping("/getOpenid/{code}")
    @ResponseBody
    public Map<String,String> decodeUserInfo(@PathVariable("code") String code) {
        // 登录凭证不能为空
        Map<String,String> map =new HashMap<>();
        if (code == null || code.length() == 0) {
            map.put("code","code 不能为空");
            return map;
        }
        //向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        String params = "appid=" + "wx24e555c077e702f3" + "&secret=" + "da2f185559d5d14e0d98ae268d7deb7b" + "&js_code=" + code + "&grant_type=authorization_code";

        // 发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);

        JSONObject jsonObject = JSONObject.parseObject(sr);

        System.out.println(jsonObject.get("openid"));

        map.put("message","成功");
        map.put("openid", (String) jsonObject.get("openid"));
        return map;
    }

    @ApiOperation(value="WX_推荐码加入")
    @GetMapping("/createCode/{userId}/{code}")
    public Result createCode(@PathVariable("userId")String userId, @PathVariable("code")String code){
        User user = userServic.getUser(userId);
        if (user==null){
            return new Result(false, StatusCode.ERROR,"用户不存在!");
        }
        if (code!=null){
            String CodeIdUser = userServic.selectCode(code);
            if (!StringUtils.isEmpty(CodeIdUser)){
                return new Result(false, StatusCode.ERROR,"推荐码已存在,请重新输入!");
            }
            userServic.createCode(userId,code);
            return new Result(true, StatusCode.OK,"推荐码加入成功!");
        }
        return new Result(false, StatusCode.ERROR,"推荐码不能为空!");
    }
    @ApiOperation(value="PC_userId用户查询")
    @GetMapping("/getUser/{userId}")
    public Result getUser(@PathVariable("userId")String userId){
            User user =userServic.getUser(userId);
            return new Result(true, StatusCode.OK,"用户查询成功!",user);
    }
    @ApiOperation(value="PC_获取管理员")
    @GetMapping("/getAdmin/{username}")
    public Result getAdmin(@PathVariable("username")String username){
            Admin admin =userServic.getAdmin(username);
            return new Result(true, StatusCode.OK,"用户管理员成功!",admin);
    }
    //查询所有
    @ApiOperation(value="PC_分页查询用户")
    @PostMapping("/findAllUser")
    public PageResult findAllUser(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = userServic.findAll(queryPageBean.getQueryString(),queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        return pageResult;
    }
    //查询所有管理员
    @ApiOperation(value="PC_分页管理员查询")
    @PostMapping("/findAllAdmin")
    public PageResult findAllAdmin(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = userServic.findAllAdmin(queryPageBean.getQueryString(),queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        return pageResult;
    }
    @ApiOperation(value="获取所有用户查询")
    @GetMapping("/getUserList")
    public Result getUserList(){
        List<User> userList =userServic.getUserList();
        return new Result(true, StatusCode.OK,"用户查询成功!",userList);
    }
    @ApiOperation(value="获取用户地址")
    @GetMapping("/findByAddress/{username}")
    public  Result findByAddress(@PathVariable("username") String username){
        List<Address> addressList = userServic.findByAddress(username);
        if (addressList!=null){
            return new Result(true, StatusCode.OK,"查询地址列表成功!",addressList);
        }
        return new Result(false, StatusCode.ERROR,"查询地址列表失败!");
    };
    @ApiOperation(value="删除用户")
    @GetMapping("/deleteAdmin/{username}")
    public  Result deleteAdmin(@PathVariable("username")String username){
        Admin admin =userServic.getAdmin(username);
        Integer status = admin.getStatus();
        if (status!=2){
            return new Result(false, StatusCode.ERROR,"心里没有一点逼数吗?");
        }
        int count = userServic.deleteAdmin(username);
        if (count>0){
            return new Result(true, StatusCode.OK,"删除成功!");
        }
        return new Result(false, StatusCode.ERROR,"操作失败!");
    };
    @ApiOperation(value="删除地址")
    @GetMapping("/deleteAddress")
    public  Result deleteAddress(int id){
        int result = userServic.deleteAddress(id);
        if (result>0){
            return new Result(true, StatusCode.OK,"删除地址成功!");
        }
        return new Result(false, StatusCode.ERROR,"删除地址失败!");
    };

    @ApiOperation(value="修改地址")
    @PostMapping("/updateAddress")
    public  Result updateAddress(@RequestBody Address address){
        int result = userServic.updateAddress(address);
        if (result>0){
            return new Result(true, StatusCode.OK,"更新地址成功!");
        }
        return new Result(false, StatusCode.ERROR,"更新地址失败!");
    };
    @ApiOperation(value="添加地址")
    @PostMapping("/insertAddress")
    public  Result insertAddress(@RequestBody Address address){
        int result = userServic.insertAddress(address);
        if (result>0){
            return new Result(true, StatusCode.OK,"添加地址成功!");
        }
        return new Result(false, StatusCode.ERROR,"添加地址失败!");
    };
    @ApiOperation(value="创建用户")
    @PostMapping("/insertUser")
    public  Result insertUser(@RequestBody User user){
        String userId = user.getUserId();
       User user1 = userServic.selectUserId(userId);
       if (user1!=null){
           return new Result(false, StatusCode.ERROR,"用户id已存在!");
       }
       if (user1!=null){
           if (user1.getUsername().equals(user.getUsername())){
               return new Result(false, StatusCode.ERROR,"者用户名已存在!");
           }
       }
        String password = AppletUtil.md5(user.getPassword());
        user.setPassword(password);
        user.setCreateTime(new Date());
        int result = userServic.insertUser(user);
        if (result>0){
            return new Result(true, StatusCode.OK,"添加用户成功!");
        }
        return new Result(false, StatusCode.ERROR,"添加用户失败!");
    };
    @ApiOperation(value="创建管理员")
    @PostMapping("/insertAdmin")
    public  Result insertAdmin(@RequestBody Admin admin){
        Admin userByAdmin = userServic.findUserByAdmin(admin.getUsername());
        if (userByAdmin!=null){
            return new Result(false, StatusCode.ERROR,"用户名已存在!");
        }
        String password = AppletUtil.md5(admin.getPassword());
        admin.setPassword(password);
        int result = userServic.insertAdmin(admin);
        if (result>0){
            return new Result(true, StatusCode.OK,"添加用户成功!");
        }
        return new Result(false, StatusCode.ERROR,"添加用户失败!");
    };
    @ApiOperation(value="修改用户信息")
    @PostMapping("/updateUser")
    public  Result updateUser(@RequestBody User user){
        String password = AppletUtil.md5(user.getPassword());
        user.setPassword(password);
        int result = userServic.updateUser(user);
        if (result>0){
            return new Result(true, StatusCode.OK,"添加地址成功!");
        }
        return new Result(false, StatusCode.ERROR,"添加地址失败!");
    };
    @ApiOperation(value="修改管理员信息")
    @PostMapping("/updateAdmin")
    public  Result updateAdmin(@RequestBody Admin admin){
        String password = AppletUtil.md5(admin.getPassword());
        admin.setPassword(password);
        int result = userServic.updateAdmin(admin);
        if (result>0){
            return new Result(true, StatusCode.OK,"添加地址成功!");
        }
        return new Result(false, StatusCode.ERROR,"添加地址失败!");
    };
}